<?php
class BulletinsController extends AppController {

	var $name = 'Bulletins';
	var $uses = array('Post', 'Repost', 'User');
	
	function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow('index', 'view');
	}
	
	function index(){
		$this->paginate = array(
			'limit' => 5, //每頁5個
			'order' => array('Post.id DESC'),
			'fields' => array('Post.*', 'User.username')
		);
		
		$data = $this->paginate('Post');
		
		//加入回覆相關資訊
		foreach($data as $key=>$post){
			$repost = $this->Repost->find(
				'first',
				array(
					'conditions'=>array(
						'Repost.post_id' => $post['Post']['id']
					),
					'order'=>array('Repost.id DESC')
				)
			);
			
			$data[$key]['Post']['post_user'] = $data[$key]['User']['username'];
			$data[$key]['Post']['post_ptime'] = $data[$key]['Post']['ptime'];
			$data[$key]['Post']['repost_user'] = $repost['User']['username'];
			$data[$key]['Post']['repost_ptime'] = $repost['Repost']['ptime'];
		}
		
		$this->set('data', $data);
	}
	
	function add(){
		
	}
	
	function delete($type=NULL, $id=NULL){
		
	}
	
	function edit($type=NULL, $id=NULL){
		
	}
	
	function view($post_id=NULL){
		$this->_emptyError($post_id, '文章引數錯誤');
		if(!$this->Post->hasAny(array('Post.id'=>$post_id))){
			$this->Session->setFlash('指定的文章不存在');
			$this->redirect(
				array(
					'controller'=>'bulletins',
					'action'=>'index'
				)
			);
		}
		$data = $this->Post->find(
			'first',
			array(
				'conditions'=>array(
					'Post.id'=>$post_id
				)
			)
		);
		
		//回應分頁
		$this->paginate = array(
			'limit'=>5,
			'order'=>array('Repost.id DESC'),
			'conditions'=>array(
				'Repost.post_id'=>$post_id
			)
		);
		
		$reposts = $this->paginate('Repost');
		
		//處理回應的陣列
		foreach($reposts as $key=>$repost){
			$user = $this->User->find(
				'first',
				array(
					'conditions'=>array(
						'User.id'=>$repost['Repost']['user_id']
					)
				)
			);
			
			$reposts[$key]['Repost']['username'] = $user['User']['username'];
		}
		
		$this->set('data', $data);
		$this->set('reposts', $reposts);
	}
	
	function _emptyError($param=NULL, $err_msg=NULL){
		if($param==NULL || $err_msg==NULL){	
			if($err_msg!=NULL)
				$this->Session->setFlash($err_msg);
			else
				$this->Session->setFlash('參數錯誤');
			$this->redirect(
				array(
					'controller'=>'bulletins',
					'action'=>'index'
				)
			);
		}
	}
}
?>